"""
简单的web服务端
"""
from socket import *
from select import select
import re
class WebServer:
    def __init__(self, host=None, port=None, html=None):
        self.host=host
        self.port=port
        self.addr=(self.host,self.port)
        self.html=html
        self.sock=self.__set_scok()
        self.rlist,self.wlist,self.xlist=[],[],[]
    def start(self):
        self.sock.listen(5)
        print("listen the port",self.port)
        self.rlist.append(self.sock)
        while True:
            rs,ws,xs=select(self.rlist,self.wlist,self.xlist)
            for r in rs:
                if r is self.sock:
                    self.__connect(r)
                else:
                    self.__handle(r)
                    self.rlist.remove(r)
                    r.close()
            # for w in ws:
            #     self.__do_response(w)

    def __set_scok(self):
        sock=socket()
        sock.bind(self.addr)
        # sock.listen(5)
        sock.setblocking(False)
        return sock

    def __connect(self, r):
        conn,addr=r.accept()
        conn.setblocking(False)
        print("Connect from:",addr)
        self.rlist.append(conn)

    def __handle(self, conn):
        request=conn.recv(1024).decode()
        # if not request:
        #     self.rlist.remove(r)
        #     r.close()
        #     return
        try:
            info=re.search(r"[A-Z]+\s+(/\S*)",request).group(1)
            print("INFO IS",info)
        except:
            return
        else:
            #组织响应
            self._reponse(conn, info)


    def _reponse(self, conn, info):
        if info=="/":
            with open("static/index.html","rb") as f:
                data=f.read()

            response = "HTTP/1.1 200 OK\r\n" + "Content-Type:text/html\r\n" + "\r\n"
            response=response.encode()+data
            conn.send(response)
        else:
            html_name=info
            try:
                file=open(self.html+html_name,"rb")
            except:
                with open(self.html+"/404.html","rb") as file1:
                    data01=file1.read()

                response = "HTTP/1.1 404 NOTFOUND\r\n" + "Content-Type:text/html\r\n" + "\r\n"
                response=response.encode()
                response=response+data01
                # conn.send(response.encode())
            else:
                data = file.read()
                response = "HTTP/1.1 200 OK\r\n" + "Content-Type:text/html\r\n" + "\r\n"
                response = response.encode() + data
                # conn.send(response)
            finally:
                conn.send(response)


if __name__ == '__main__':
    #类的参数  host port 网页
    httpd=WebServer(host="0.0.0.0",port=5288,html="/home/tarena/month02/day17/static")
    httpd.start()